package com.tpshion.chat.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class MyExceptionAdvice {

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public ResponseVo myExceptionHandler(MyException e){
        log.info("业务异常："+e.getCode()+"--"+e.getMessage());
        return ResponseVo.buildException(e);
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseVo defaultException(Exception e){
        log.info("系统异常："+e.getMessage());
        ResponseVo responseVo = null;
        if(e instanceof HttpMessageNotReadableException){
            //请求参数为空异常
            responseVo = ResponseVo.buildSystemException(RespStatus.PARAM_NOFUND);
        }else if(e instanceof HttpRequestMethodNotSupportedException){
            //请求方法类型错误异常
            responseVo = ResponseVo.buildSystemException(RespStatus.REQUEST_TYPE_ERROR);
        } else{
            log.error("系统未处理异常：",e);
            responseVo = ResponseVo.buildSystemException(RespStatus.ERROR);
        }
        return responseVo;
    }
}
